# -*- coding: utf-8 -*-
import traceback
from utils.backcode import ImportError
from app.manage.userManage.common.manage_sql import UserManageSql
import hashlib
from utils.logger import Md_Debug
from utils.db_utils import DbConn
import datetime


class UserManageDB(object):
    """视频"""
    def __init__(self):
        self.db = DbConn()
        self.now = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d")

    def user_login(self, body):
        """用户登录"""
        try:
            picVisit = dict()
            db = DbConn()
            user_name = body.get('user_name', None)
            user_passwd = body.get('user_passwd', None)
            role_id = ""

            # check parameter
            if not user_name:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "user_name is none"
            elif not user_passwd:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "user_passwd is none"
            else:
                user_passwd = hashlib.sha256(user_passwd).hexdigest()
                param = [user_name, user_passwd]
                login_back = db.fetch_one(UserManageSql.USER_LOGIN, param)
                
                if not login_back:
                    code = ImportError.IMPORT_CODE_RECORD_NOT_FOUND
                    message = "用户名或密码错误"
                    user_name = " "
                    role_id = " "
                    user_id = " "
                else:
                    role_id = login_back['role_id']
                    user_id = login_back['id']
                    picVisit['company_post'] = login_back.get('company_post')
                    picVisit['department'] = login_back.get('department')
                    picVisit['role_id'] = login_back.get('role_id')
                    permitList = UserManageDB.user_permit_list(self, login_back['id'])
                    code = ImportError.IMPORT_CODE_SUCCESS
                    picVisit['response_data'] = permitList
                    message = "success"
        except Exception as e:
            user_name = " "
            role_id = " "
            user_id = " "
            code = ImportError.IMPORT_CODE_EXCEPTION
            message = str(e)
            Md_Debug.error(traceback.format_exc(e))
            print(traceback.format_exc(e))
        picVisit['role_id'] = role_id
        picVisit['uer_name'] = user_name
        picVisit['user_id'] = user_id
        picVisit['response_code'] = code
        picVisit['response_msg'] = message
        return picVisit

    def user_list(self, body):
        """用户列表查看"""
        try:
            userList = dict()
            db = DbConn()
            user_name = body.get('user_name', None)
            page = body.get('page', None)
            size = body.get('size', None)

            # check parameter
            if not page:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "page is none"
            elif not size:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "size is none"
            else:
                SQL = UserManageSql.USER_LIST
                if user_name:
                    SQL = UserManageSql.USER_LIST + " AND user_name LIKE '%%%%%s%%%%' " % user_name
                user_list = db.fetch_all(SQL)

                paging_back = UserManageDB.paging(self, user_list, page, size)
                code = ImportError.IMPORT_CODE_SUCCESS
                message = paging_back['data']
                userList['total_page'] = paging_back['total_page']
                userList['total_size'] = paging_back['total_size']
                userList['page'] = paging_back['page']
                userList['size'] = paging_back['size']
        except Exception as e:
            code = ImportError.IMPORT_CODE_EXCEPTION
            message = str(e)
            Md_Debug.error(traceback.format_exc(e))
            print(traceback.format_exc(e))
        userList['response_code'] = code
        userList['response_msg'] = message
        return userList

    def user_list_permit(self, body):
        """用户列表查看"""
        try:
            userList = dict()
            db = DbConn()
            user_name = body.get('user_name', None)
            page = body.get('page', None)
            size = body.get('size', None)

            # check parameter
            if not page:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "page is none"
            elif not size:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "size is none"
            else:
                SQL = UserManageSql.USER_LIST
                if user_name:
                    SQL = UserManageSql.USER_LIST + " AND user_name LIKE '%%%%%s%%%%' " % user_name
                user_list = db.fetch_all(SQL)
                for i in range(len(user_list)):
                    if user_list[i]['role_id'] == 1:
                        user_list.remove(user_list[i])
                        break
                paging_back = UserManageDB.paging(self, user_list, page, size)
                code = ImportError.IMPORT_CODE_SUCCESS
                message = paging_back['data']
                userList['total_page'] = paging_back['total_page']
                userList['total_size'] = paging_back['total_size']
                userList['page'] = paging_back['page']
                userList['size'] = paging_back['size']
        except Exception as e:
            code = ImportError.IMPORT_CODE_EXCEPTION
            message = str(e)
            Md_Debug.error(traceback.format_exc(e))
            print(traceback.format_exc(e))
        userList['response_code'] = code
        userList['response_msg'] = message
        return userList

    def all_user(self):
        """所有成员"""
        try:
            ret = dict()
            data = self.db.fetch_all(UserManageSql.ALL_USER)
            code = ImportError.IMPORT_CODE_SUCCESS
            message = data
        except Exception as e:
            code = ImportError.IMPORT_CODE_EXCEPTION
            message = str(e)
            Md_Debug.error(traceback.format_exc(e))
            print(traceback.format_exc(e))
        ret['response_code'] = code
        ret['response_msg'] = message
        return ret

    def user_permit_list(self, user_id):
        """用户权限列表"""
        try:
            db = DbConn()
            menuList = []
            permitList = []
            permit_back = db.fetch_all(UserManageSql.USER_PEIMIT_LIST, [user_id])
            for i in range(len(permit_back)):
                if permit_back[i]['menu_name'] in menuList:
                    pass
                else:
                    menuList.append(permit_back[i]['menu_name'])

            for i in range(len(menuList)):
                permitList.append({"menu_name": menuList[i]})

            for i in range(len(permit_back)):
                for i1 in range(len(permitList)):
                    if permit_back[i]['menu_name'] == permitList[i1]['menu_name']:
                        permitList[i1]['menu_url'] = permit_back[i]['menu_url']
                        permitList[i1]['menu_id'] = permit_back[i]['menu_id']
                        permitList[i1]['children'] = []

            for i in range(len(permit_back)):
                for i1 in range(len(permitList)):
                    if permit_back[i]['menu_name'] == permitList[i1]['menu_name']:
                        ret = dict()
                        ret['second_menu_name'] = permit_back[i]['second_menu_name']
                        ret['second_menu_url'] = permit_back[i]['second_menu_url']
                        permitList[i1]['children'].append(ret)
        except Exception as e:
            Md_Debug.error(traceback.format_exc(e))
            print(traceback.format_exc(e))
        return permitList

    def permit_list(self):
        """权限列表"""
        try:
            perList = dict()
            db = DbConn()
            perList_back = db.fetch_all(UserManageSql.PERMIT_LIST)
            code = ImportError.IMPORT_CODE_SUCCESS
            message = perList_back
        except Exception as e:
            code = ImportError.IMPORT_CODE_EXCEPTION
            message = str(e)
            Md_Debug.error(traceback.format_exc(e))
            print(traceback.format_exc(e))
        perList['response_code'] = code
        perList['response_msg'] = message
        return perList

    def user_permit(self):
        """用户对应权限列表"""
        try:
            userList = dict()
            ret = dict()
            menuList = []
            db = DbConn()
            user_permit_back = db.fetch_all(UserManageSql.USER_TO_PERMIT_LIST)
            for i in range(len(user_permit_back)):
                if user_permit_back[i]['user_name']in menuList:
                    pass
                else:
                    menuList.append(user_permit_back[i]['user_name'])
            for i in range(len(menuList)):
                ret[menuList[i]] = []
            for i in range(len(user_permit_back)):
                ret[user_permit_back[i]['user_name']].append(user_permit_back[i]['menu_name'])
            code = ImportError.IMPORT_CODE_SUCCESS
            message = ret
        except Exception as e:
            code = ImportError.IMPORT_CODE_EXCEPTION
            message = str(e)
            Md_Debug.error(traceback.format_exc(e))
            print(traceback.format_exc(e))
        userList['response_code'] = code
        userList['response_msg'] = message
        return userList

    def paging(self, dataList, page, size):
        """分页"""
        ret = {
               'page': page, 'size': size, 'total_page': 0, 'total_size': 0
               }
        total_size = len(dataList)
        if total_size % size == 0:
            total_page = total_size / size
        else:
            total_page = total_size / size + 1
        start_index = (page - 1) * size
        end_index = page * size
        ret['total_page'] = total_page
        ret['total_size'] = total_size
        ret['data'] = dataList[start_index: end_index]
        return ret



